package com.top.mall.jetpack.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.module.lemlin.http.HttpResponseBody
import com.module.lemlin.http.SubscribeViewModel
import com.top.mall.app.BaseApplication
import com.top.mall.entity.*
import com.top.mall.jetpack.ma.CartManager
import com.top.mall.base.BaseViewModel

open class CartViewModel(application: Application) : BaseViewModel(application) {

    private val cartManager: CartManager = CartManager()

    val cartListLiveData = MutableLiveData<HttpResponseBody<CartListResponse>>()
    val cartAddLiveData = MutableLiveData<HttpResponseBody<CartAddResponse>>()
    val cartChangeNumLiveData = MutableLiveData<HttpResponseBody<CartChangeNumResponse>>()
    val cartDeleteLiveData = MutableLiveData<HttpResponseBody<CartDeleteResponse>>()

    /**
     * 购物车列表
     */
    fun cartIndex() {
        val listener = object : SubscribeViewModel<CartListResponse>(cartListLiveData) {
            override fun onSuccess(resp: CartListResponse) {
                resp.data.cartList.forEach {
                    it.isSelected = BaseApplication.appDatabase.accountDao()
                        .selectCartSelectedByShopIdAndCartId(
                            BaseApplication.SHOP_ID,
                            it.cart_id
                        ) != null
                }
                super.onSuccess(resp)
                BaseApplication.setCartListLiveData(resp.data.cartList)
            }
        }
        setRxLifeScope(listener) {
            cartManager.cartIndex()
        }
    }


    val settlementCartLiveData = MutableLiveData<HttpResponseBody<SettlementCartResponse>>()
    fun cartSettlement(cartList: Array<Int>) {
        setRxLifeScope(SubscribeViewModel(settlementCartLiveData)) {
            cartManager.cartSettlement(cartList)
        }
    }

    /**
     * 加入购物车
     * */
    fun cartAdd(goodsId: Int, goodsNum: Int, position: Int) {
        val listener = object : SubscribeViewModel<CartAddResponse>(cartAddLiveData) {
            override fun onSuccess(resp: CartAddResponse) {
                super.onSuccess(resp.apply {
                    this.position = position
                    this.goods_num = goodsNum
                    this.cart_id = try {
                        resp.data.toInt()
                    } catch (e: Exception) {
                        0
                    }
                })
                //加入购物车时默认设置选中
                updateCartListSelected(goodsId, resp.cart_id, (true))
                //刷新购物车列表数据
                cartIndex()
            }
        }
        setRxLifeScope(listener) {
            cartManager.cartAdd(goodsId, goodsNum)
        }
    }

    /**
     *购物车数量加减
     * */
    fun cartChangeNum(
        cartId: Int, goodsNum: Int, position: Int, isSelected: Boolean? = null
    ) {
        val listener = object : SubscribeViewModel<CartChangeNumResponse>(cartChangeNumLiveData) {
            override fun onSuccess(resp: CartChangeNumResponse) {
                super.onSuccess(resp.apply {
                    this.cart_id = cartId
                    this.goods_num = goodsNum
                    this.position = position
                })
                updateCartListLiveData(CartType.UPDATE, cartId, goodsNum, isSelected)
            }
        }
        setRxLifeScope(listener) {
            cartManager.cartChangeNum(cartId, goodsNum)
        }
    }

    /**
     * 购物车删除
     * */
    fun cartDelete(cartIds: Array<Int>, type: CartType, position: Int = -1) {
        val listener = object : SubscribeViewModel<CartDeleteResponse>(cartDeleteLiveData) {
            override fun onSuccess(resp: CartDeleteResponse) {
                super.onSuccess(resp.apply { this.position = position })
                if (type == CartType.DELETE) {
                    updateCartListLiveData(type, cartId = cartIds[0])
                } else if (type == CartType.CLEAR) {
                    updateCartListLiveData(type)
                }
            }
        }
        setRxLifeScope(listener) {
            cartManager.cartDelete(cartIds)
        }
    }

    /**
     * 更改数据
     * */
    fun updateCartListLiveData(
        type: CartType, cartId: Int = 0, goodsNum: Int? = null, isSelected: Boolean? = null
    ) {
        BaseApplication.getCartListLiveData().value?.let { cartList ->
            when (type) {
                CartType.CLEAR -> {
                    cartList.clear()
                }
                CartType.DELETE -> cartList.find { it.cart_id == cartId }?.let {
                    cartList.remove(it)
                }
                CartType.UPDATE -> cartList.find { it.cart_id == cartId }?.apply {
                    this.goods_num = goodsNum ?: this.goods_num
                    this.isSelected = isSelected ?: this.isSelected
                    updateCartListSelected(this.goods_id, this.cart_id, this.isSelected)
                }
                CartType.SELECTED -> for (index: Int in 0 until cartList.size) {
                    cartList[index].apply {
                        this.isSelected = isSelected ?: this.isSelected
                        updateCartListSelected(this.goods_id, this.cart_id, this.isSelected)
                    }
                }
                else -> {
                }
            }
            BaseApplication.setCartListLiveData(cartList)
        }
    }

    /**
     * 更改数据库购物车是否选中
     * */
    private fun updateCartListSelected(goodsId: Int, cartId: Int, isSelected: Boolean) {
        val shopId: Int = 1
        if (isSelected) {
            //新增
            BaseApplication.appDatabase.accountDao().insert(CartSelected().apply {
                this.shopId = shopId
                this.goodsId = goodsId
                this.cartId = cartId
            })
        } else {
            //删除
            BaseApplication.appDatabase.accountDao().delete(shopId, cartId)
        }
    }

}